<?php

namespace App\Http\Controllers;

use Log;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Qiniu\Auth;
use App\Models\AppVersion;
use App\Models\Resource;
use App\Utils\ReturnUtils;
use App\Cache\BaseCache;
use App\Models\BaseModel;
use App\Utils\CommonUtils;
use Cache;
use App\Utils\RouteLists;
use App\Models\Feedback;
use Illuminate\Contracts\View\View;
use App\Cache\MessageHandle;
use App\Models\Content;
use App\Models\Comment;
use App\Models\User;
use App\Models\Topic;
use App\Models\Program;
use App\Cache\MRedis;
class SysController extends Controller {

    public function readLogs(Request $request) {
//        with(new CommonUtils($request))->readStreamFile();
//        exit();
//        with(new CommonUtils($request))->sendShortMessage('11');
//        exit();
        $info['page'] = $request->input('page', '1');
        $info['day'] = $request->input('day', '0000000');
        $info['file'] = $request->input('file');
        //读取当日日志
        //发送get请求
        if ($info['page'] < 1) {
            return 'Error page';
        }
        if ($info['file'] == 'workman') {
            $filename = __DIR__ . '/../../Service/workman/logs/workman.log';
            if (!file_exists($filename)) {
                echo $filename . '日志文件不存在';
                Log::info($filename . '日志文件不存在');
                return;
            }
        } else {
            $filename = __DIR__ . '/../../../storage/logs/lumen-' . date("Y-m-d", time() - $info['day'] * 24 * 60 * 60) . '.log';
            if (!file_exists($filename)) {
                echo $filename . '日志文件不存在';
                Log::info($filename . '日志文件不存在');
                return;
            }
        }
        $fp = fopen($filename, "r");
        $totalPage = (int) (filesize($filename) / 8192 + 1);
        if ($totalPage < $info['page']) {
            $info['page'] = $totalPage;
        }
        fseek($fp, -8192 * $info['page'], SEEK_END);
        $data = fread($fp, 8192);
        $data = str_replace(' #', '<br>#', $data);
        echo '<pre>';
        echo '<h2>日期：' . date("Y-m-d", time() - $info['day'] * 24 * 60 * 60) . '总共： ' . $totalPage . '页，第' . $info['page'] . '页<br/></h2>';
        echo $data;
    }
    
    public function sendMessageToApi(Request $request){
        $returnUtils = new ReturnUtils($request);
        $message = $request->input('message');
        $ret = with(new MessageHandle())->handle($message);  
        if(!$ret){
            return $returnUtils->returnError($returnUtils->return['ERROR_UNKNOWN']);
        }
        return $returnUtils->returnOk($returnUtils->return['SUCCESS']);
    }
    
    public function syncDataFromTv(Request $request){
        return 'welcome to beijing';
    }
    
    public function getUuid(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $id = $request->input('id');
        $data['uuid'] = with(new CommonUtils($request))->getUuid($id);
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $data);
    }

    public function getApiStatistic(Request $request) {
        $debugCache = new BaseCache();
        $debugCache->method = 'get';
        $debugCache->cacheName = 'getCacheKeyList';
        $debugCache->cachePar = array('debug'); //集合
        $retCache = $debugCache->HandleCache();
        echo '-----------------------------------------------------------------------' . '<br>';
        echo ' - record_data : 记录时间' . '<br>';
        echo ' - times : 调取接口总次数' . '<br>';
        echo ' - sum_time : 调取接口总时间' . '<br>';
        echo ' - has_sql_times : 调取接口有多少次需要操作数据库' . '<br>';
        echo ' - sum_sql_times : 调取接口总共操作多少次数据库' . '<br>';
        echo ' - sum_sql_time : 调取接口数据库操作总耗时' . '<br>';
        echo '-----------------------------------------------------------------------' . '<br>';
        if (!is_array($retCache)) {
            return;
        }
        foreach ($retCache as $value) {
            if (!isset($value['key'])) {
                continue;
            }
            $debugCache->cacheName = 'debug';
            $action = str_replace(env('USER_PRE', 'joymedia') . $debugCache->cacheName, '', $value['key']);
            $debugCache->cachePar = array($action); //集合
            $ret = $debugCache->HandleCache();
            if (isset($ret['times']) && $ret['times'] > 1) {
                echo '<== ' . $action . ' ==> ' . json_encode($ret) . '<br>';
            }
        }
    }

    public function testApi(Request $request) {
        set_time_limit(600);
        $method = $request->input('method');
        $url = $request->input('url');
        $par = $request->input('par');
        $varPar = $request->input('varPar');
        $times = $request->input('times');
        $par_array = json_decode($par, TRUE);
        $varPar = json_decode($varPar, TRUE);
        if (!is_array($par_array) || !is_array($varPar)) {
            echo 'par varPar 参数格式不对';
            return;
        }
        foreach ($par_array as $key => $value) {
            foreach ($varPar as $value1) {
                if ($value1 == $key) {
                    $par_array[$key] = $value . time() . ',' . rand(100000, 999999);
                    continue;
                }
            }
        }
        if ($method == 'get') {
            $url = $url . '?';
            $par_str = null;
            foreach ($par_array as $key => $value) {
                if (!$par_str) {
                    $par_str = $key . '=' . $value;
                    continue;
                }
                $par_str .= '&' . $key . '=' . $value;
            }
            $url .= $par_str;
            echo $url;
            for ($i = 0; $i < $times; $i++) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                $ret = curl_exec($ch);
                curl_close($ch);
            }
        } else {
            for ($i = 0; $i < $times; $i++) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $par_array);
                curl_exec($ch);
                curl_close($ch);
            }
        }
        Log::info('testApi' . 'method:' . $method . ' url:' . $url);
    }

    //七牛回调
    public function qiNiu(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $info = $request->all();
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $info);
    }

    //获取七牛token
    public function qiNiuUpToken(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $bucket = env('QINIU_BUCKET');
        $callbackBody = env('QINIU_CALLBACK_BODY');
        $callbackUrl = env('HTTP_HOST') . env('QINIU_CALLBACK');
        $data = array();
        $data['upToken'] = $this->getUptoken($accessKey, $secretKey, $bucket, $callbackUrl, $callbackBody);
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $data);
    }

    /*
     * 获取七牛Token
     */
    public function getUptoken($accessKey, $secretKey, $bucket, $callbackUrl, $callbackBody) {
        //获取qiniu配置
        $auth = new Auth($accessKey, $secretKey);
        $key = null;
        $expires = 3600;
        $policy = array(
            'CallbackUrl' => $callbackUrl,
            'CallbackBody' => $callbackBody,
        );
        $strictPolicy = FALSE;
        $token = $auth->uploadToken($bucket, $key, $expires, $policy, $strictPolicy);
        return $token;
    }

    // 获取微信分享config
    public function getWxConfig() {
        $wx_appid = env('WX_APPID');
        $wx_secret = env('WX_SECRET');
        $cache = new BaseCache();
        $cache->method = 'get';
        $cache->cacheName = 'WenXinConfig';
        $retCache = $cache->HandleCache();
        if(isset($retCache['token'])){
            return $retCache;
        }
        //缓存1小时
        $wx_config = array();
        //发请求获取 token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wx_appid . '&secret=' . $wx_secret;
        try {
            $return_str = file_get_contents($url);
            $return = json_decode($return_str);
            if (!isset($return->access_token)) {
                $return_str = file_get_contents($url);
                $return = json_decode($return_str);
            }
            if (isset($return->access_token)) {
                //发送第二个请求
                $url_js = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $return->access_token . '&type=jsapi';
                $return_jsstr = file_get_contents($url_js);
                $return_js = json_decode($return_jsstr);
                if ($return_js->errcode == 0) {
                    $wx_config['ticket'] = $return_js->ticket;
                    $wx_config['token'] = $return->access_token;
                    $wx_config['appid'] = $wx_appid;
                    $cache->method = 'put';
                    $cache->cacheValue = $wx_config;
                    $retCache = $cache->HandleCache();
                }
            }
        } catch (\Exception $exc) {
            
        }
        return $wx_config;
    }
    
    //获取wx js config
    public function getWxJsConfig(Request $request) {
        $url = $request->input('url');
        $returnUtils = new ReturnUtils($request);
        $wxConfig = $this->getWxConfig();
        $str = '';
        $timestamp = time();
        $noncestr = uniqid();
        $appid = '';
        if ($wxConfig) {
            $str = 'jsapi_ticket=' . $wxConfig['ticket'] . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url=' . $url;
            $appid = $wxConfig['appid'];
        }
        $return_arr = array(
            'appId' => $appid,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => sha1($str),
        );
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $return_arr);
    }
    
    public function toastMessage(Request $request) {
        $message = $request->input('message');
        Log::info('toastMessage:' . $message);
        return $message;
    }

    //代码生成路由控制器
    public function initRouterAndController(Request $request) {
        //控制器目录
        $controller_root_dir = __DIR__;
        //路由文件目录
        $route_dir = __DIR__ . '/../../../routes';
        //判断目录是否存在
        if (!is_dir($controller_root_dir) || !is_dir($route_dir)) {
            return 'error';
        }
        $routeLists = new RouteLists();
        $route_arr = $routeLists->lists;
        if (is_array($route_arr)) {
            //遍历路由列表
            foreach ($route_arr as $name => $route) {
                //ChildrenWap\ProgramController@getProgramList
                $index = explode('@', $name);
                if (count($index) !== 2) {
                    continue;
                }
                //函数名
                $function_name = $index[1];
                //控制器目录
                $controller_dir = NULL;
                //控制器文件名称
                $controller_name = null;
                //请求方式
                $method = $route['method'];
                //请求路由地址
                $route_name = $route['route'];
                $annotation = isset($route['annotation']) ? $route['annotation'] : '';
                $index = explode('\\', $index[0]);
                if (isset($index[1])) {
                    $controller_name = $index[1];
                    $controller_dir = $index[0];
                } else {
                    $controller_name = $index[0];
                }

                /*                 * **************生成控制器**************** */
                $tag_dir = $controller_root_dir; //目标控制器的目录
                if ($controller_dir) {
                    if (!is_dir($tag_dir . '/' . $controller_dir)) {
                        mkdir($tag_dir . '/' . $controller_dir, 0755, TRUE);
                    }
                    $tag_dir .= '/' . $controller_dir;
                }
                $tag_file_dir = $tag_dir . '/' . $controller_name . '.php';
                $content = null;
                if (file_exists($tag_file_dir)) {
                    $content = file_get_contents($tag_file_dir);
                }
                //控制器不存在
                if (!$content) {
                    //获取空控制器
                    $content = $this->getTemplate('cotroller');
                    $nameSpace = 'App\\Http\\Controllers';
                    //替换命名空间 App\Http\Controllers
                    if ($controller_dir) {
                        $nameSpace .= '\\' . $controller_dir;
                    }
                    $content = str_replace("##命名空间##", $nameSpace, $content);
                    //替换控制器名称
                    $content = str_replace("##控制器名##", $controller_name, $content);
                }
                //判断是否存在函数
                if (!strpos($content, $function_name . '(Request $request)')) {
                    //不存在，加入函数
                    $function_str = $this->getTemplate('function');

                    ##注释##
                    $function_str = str_replace('##注释##', '//' . $annotation, $function_str);
                    $function_str = str_replace('##函数名##', $function_name, $function_str);
                    $mark_str = $this->getTemplate('markFuction');
                    $content = str_replace($mark_str, $function_str, $content);
                }
                //控制器初始化
                file_put_contents($tag_file_dir, $content);
//                
                //路由初始化
                $routes_file_name = $route_dir . '//routes.php';
                $routes_content = file_get_contents($routes_file_name);
                //判断路由是否存在
//                 $app->get('/children/tv/getConfig', 'ChildrenTv\SystemController@getConfig');
                $route_str1 = "'" . $route_name . "'";
                $route_str2 = "'" . $controller_name . '@' . $function_name . "'";
                if ($controller_dir) {
                    $route_str2 = "'" . $controller_dir . '\\' . $controller_name . '@' . $function_name . "'";
                }
                if (!strpos($routes_content, $route_str1)) {
                    $index_route = '$app->' . $method . '(' . $route_str1 . ',' . $route_str2 . ')';
                    $template_router = $this->getTemplate('router');
                    $template_router = str_replace('##注释##', '//' . $annotation, $template_router);
                    $template_router = str_replace('##路由##', $index_route, $template_router);
                    //加入路由
                    switch ($controller_dir) {
                        case 'Cbn':
                            $template_router = str_replace('##路由组##', '/**国广项目路由组**/', $template_router);
                            $routes_content = str_replace('/**国广项目路由组**/', $template_router, $routes_content);
                            break;
                        case NULL:
                            $template_router = str_replace('##路由组##', '/**公共项目路由组**/', $template_router);
                            $routes_content = str_replace('/**公共项目路由组**/', $template_router, $routes_content);
                            break;
                        default :
                            $routes_content = null;
                            break;
                    }
                    if ($routes_content) {
                        file_put_contents($routes_file_name, $routes_content);
                    }
                }
            }
        }
        //自动生成模型
        $tables = DB::connection(env('MYSQL_CONNECTION', 'mysql'))->select('show tables');
        foreach ($tables as $key => $table) {
            $db_table_name = 'Tables_in_' . env('DB_DATABASE');
            $db_table_name = $table->$db_table_name;
            $db_table_pri = 'id';
            $getItems = DB::connection(env('MYSQL_CONNECTION', 'mysql'))->select('show columns from ' . $db_table_name);
            foreach ($getItems as $key => $item) {
                if ($item->Key === 'PRI') {
                    $db_table_pri = $item->Field;
                    break;
                }
            }
            $model_name = '';
            $index_arr = explode('_', $db_table_name);
            foreach ($index_arr as $key => $value) {
                $model_name .= strtoupper(substr($value, 0, 1)) . substr($value, 1, strlen($value));
            }
            //##模型名## $model_name
            $template_model = $this->getTemplate('model');
            $template_model = str_replace('##模型名##', $model_name, $template_model);
            $template_model = str_replace('##主键##', $db_table_pri, $template_model);
            $template_model = str_replace('##表名##', $db_table_name, $template_model);
            //模型目录
            $dir_model = __DIR__ . '/../../Models';
            $file_model_name = $dir_model . '/' . $model_name . '.php';
            if (!file_exists($file_model_name)) {
                file_put_contents($file_model_name, $template_model);
            }
        }
        
    }

    //获取模版
    public function getTemplate($template) {
        if ($template !== 'cotroller' && $template !== 'function' &&
                $template !== 'model' && $template !== 'markFuction' &&
                $template !== 'router' && $template !== 'model' &&
                $template !== 'apiDoc' ) {
            return;
        }
        $content = '';
        $dir_template = __DIR__ . '/../../Utils/Template';
        $filename = $dir_template . '/' . $template;
        $content = file_get_contents($filename);
        return $content;
    }

    //获取接口文档
    public function getApiDoc(Request $request) {
        //生成接口DOC
        $dir_doc =  __DIR__ . '/../../Utils/ApiDoc';
        $file_name = $dir_doc . '/' . env('USER_PRE') . 'Doc.php';
        if (!file_exists($file_name)) {
            $template_model = $this->getTemplate('apiDoc');
            $template_model = str_replace('##CLASSNAME##',env('USER_PRE').'Doc',$template_model);
            file_put_contents($file_name, $template_model);
        }
        $class = '\\App\\Utils\\ApiDoc\\'.env('USER_PRE').'Doc';
        $apiDoc = new $class();
        
        $return = new ReturnUtils($request);
        $retrunCode = $return->return;
        
        $routeLists = new RouteLists();
        $routeList = $routeLists->lists;
        foreach ($routeList as $key => $route) {
             //处理返回
            if(isset($route['rules']['1']['return'])){
                $routeList[$key]['rules']['1']['return'] = json_encode(json_decode($route['rules']['1']['return']));
            }
            if($routeList[$key]['rules']['1']['return'] === 'null'){
                $routeList[$key]['rules']['1']['return'] = '';
            }
            if($key == 'SysController@getApiDoc' 
                    || $key == 'SysController@initRouterAndController'
                    || $key == 'SysController@writeReidsObject'
                    || $key == 'SysController@feedback'){
                unset($routeList[$key]);
                continue;
            }
            $index = explode('\\', $key);
            if(count($index) > 1){
                if(strtolower($index['0']) != strtolower(env('USER_PRE'))){
                    unset($routeList[$key]);
                };
            }
        }
//            //##模型名## $model_name
//            $template_model = $this->getTemplate('model');
//            $template_model = str_replace('##模型名##',$model_name,$template_model);
//            $template_model = str_replace('##主键##',$db_table_pri,$template_model);
//            $template_model = str_replace('##表名##',$db_table_name,$template_model);
//            //模型目录
//            $dir_model = __DIR__.'/../../Models';
//            $file_model_name = $dir_model.'/'.$model_name.'.php';
//            if(!file_exists($file_model_name)){
//                file_put_contents($file_model_name, $template_model);
//            }
        $data = array(
            'routeList'=>$routeList,
            'information'=>$apiDoc->information,
            'retrunCode'=>$retrunCode,
            'modificationRecord'=> array_reverse($apiDoc->modificationRecord),
        );
        return view('apiDoc',$data);
    }
    //获取关于
    public function writeReidsObject(Request $request) {
        $table = $this->request->input('table');
        $itemId = $this->request->input('id');
        $arrIds = explode(',', $itemId);
        $ObjData = '';
        switch ($table){
            case 'content':
                $ObjData = Content::select('*')
                    ->where('is_delete','=',0)
                    ->where('status','=',1);
//                    ->get();
                break;
            case 'comment':
                $ObjData = Comment::select('*')
                    ->where('is_delete','=',0)
                    ->where('status','=',1);
//                    ->get();
                break;
            case 'user':
                $ObjData = User::select('*')
                    ->where('is_delete','=',0)
                    ->where('status','=',1);
//                    ->get();
                break;
            case 'topic':
                $ObjData = Topic::select('*')
                    ->where('is_delete','=',0)
                    ->where('status','=',1);
//                    ->get();
                break;
            case 'program':
                $ObjData = Program::select('*')
                    ->where('is_delete','=',0);
//                    ->get();
                break;
        }
        if(count($arrIds) > 0){
            $ObjData = $ObjData->wherIn('id',$arrIds);
        }
        $ObjData = $ObjData->get();
        if($ObjData){
            $itemArr = [];
            $mRedis = new MRedis();
            foreach ($ObjData as $key=>$val){
//                $ret = $mRedis->handleEntity('add', $table, $val->id);
                $ret = TRUE;
                if($ret){
                    $itemArr[] = $val->id;
                }
            }
            Log::info("加入redis缓存的实体id:". json_encode($itemArr));
            return TRUE;
        }
        Log::info("并没有写入任何数据");
        return TRUE;
    }
    /*     * *****************************************SMARTCONTROLLER********************************************* */
}
